package com.example.orderservice.controller;

import com.example.orderservice.event.OrderEvent;
import com.example.orderservice.service.EventQueryService;
import com.example.orderservice.actor.PersistentOrderActor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletionStage;

/**
 * 事件查询控制器
 * 提供事件溯源查询的REST API
 */
@Slf4j
@RestController
@RequestMapping("/api/events")
public class EventQueryController {
    
    @Autowired
    private EventQueryService eventQueryService;
    
    /**
     * 查询指定订单的所有事件
     */
    @GetMapping("/orders/{orderId}")
    public CompletionStage<ResponseEntity<List<OrderEvent>>> getOrderEvents(@PathVariable String orderId) {
        log.info("查询订单事件: {}", orderId);
        
        return eventQueryService.getOrderEvents(orderId)
            .thenApply(events -> {
                if (events.isEmpty()) {
                    return ResponseEntity.notFound().build();
                }
                return ResponseEntity.ok(events);
            })
            .exceptionally(throwable -> {
                log.error("查询订单事件失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
    
    /**
     * 重建订单状态
     */
    @GetMapping("/orders/{orderId}/state")
    public CompletionStage<ResponseEntity<PersistentOrderActor.OrderState>> rebuildOrderState(@PathVariable String orderId) {
        log.info("重建订单状态: {}", orderId);
        
        return eventQueryService.rebuildOrderState(orderId)
            .thenApply(state -> {
                if (state.getOrderId() == null) {
                    return ResponseEntity.notFound().build();
                }
                return ResponseEntity.ok(state);
            })
            .exceptionally(throwable -> {
                log.error("重建订单状态失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
    
    /**
     * 查询所有订单摘要
     */
    @GetMapping("/orders/summaries")
    public CompletionStage<ResponseEntity<List<EventQueryService.OrderSummary>>> getAllOrderSummaries() {
        log.info("查询所有订单摘要");
        
        return eventQueryService.getAllOrderSummaries()
            .thenApply(summaries -> ResponseEntity.ok(summaries))
            .exceptionally(throwable -> {
                log.error("查询订单摘要失败: {}", throwable.getMessage(), throwable);
                return ResponseEntity.internalServerError().build();
            });
    }
}

